//
//  CoreDataHelper.swift
//  newsApp
//
//  Created by Tirel on 2020/5/12.
//  Copyright © 2020 Doo Psyist. All rights reserved.
//

import Foundation
import SwiftUI
import CoreData
var newsArray: [NewsCommentModel]!
var new = [NSManagedObject]()
let helper = AppDelegate()

var networkJson: [NewsListItem]!

func likeByid (_ id: Int) {
    _ = NSEntityDescription.insertNewObject(forEntityName: "News", into: helper.persistentContainer.viewContext) as! News
    let anews = findNewsbyId(id)
    if anews[0].like == false {
        anews[0].like = true;
    } else {
        anews[0].like = false;
    }
    helper.saveContext()
}




func commentByid (_ id: Int, _ cmt: String) {
    _ = NSEntityDescription.insertNewObject(forEntityName: "News", into: helper.persistentContainer.viewContext) as! News
    let anews = findNewsbyId(id)
    anews[0].comment?.append(cmt + "%%");
    helper.saveContext()
}
func initDataincoredata() {
    deleteAllNews()
    var news: NewsCommentModel = NewsCommentModel()
    networkJson = newsList
    newsList.forEach { (element) in
        print(element)
        news = NewsCommentModel(newsId: Int16(element.id), newsComment: "", newsIsliked: false, access: 0)
        print(news)
        addNewsCL(news)
    }
}
func loadDatabycoredata() {
    fetchAll().forEach { (element) in
        print(element)
    }
}

func findNewsbyId(_ id: Int) -> [News] {
    let fetchRequest: NSFetchRequest = News.fetchRequest()
    fetchRequest.predicate = NSPredicate(format: "newsid == %i", Int16(id))
    do {
        let result: [News] = try helper.persistentContainer.viewContext.fetch(fetchRequest)
        print(result[0])
        return result
    } catch let err {
        print("core data fetch error:", err)
    }
    return [News]()
}





func addNewsCL(_ arr: NewsCommentModel) {
    let news = NSEntityDescription.insertNewObject(forEntityName: "News", into: helper.persistentContainer.viewContext) as! News
    print(arr.newsId)
    news.newsid = arr.newsId
    news.like = arr.newsIsliked
    news.comment = arr.newsComment
    news.access = arr.access
    helper.saveContext()

}
func deleteAllNews() {
    for tmp in fetchAll() {
        helper.persistentContainer.viewContext.delete(tmp)
    }
    helper.saveContext()
}
func updateLike(id: Int, isLiked: Bool) -> Bool {
    let fetchRequest: NSFetchRequest = News.fetchRequest()
    fetchRequest.predicate = NSPredicate(format: "newsid == %i", Int16(id))
    let asyncFecthRequest = NSAsynchronousFetchRequest(fetchRequest: fetchRequest) { (result: NSAsynchronousFetchResult!) in
        let fetchObject = result.finalResult! 
        for c in fetchObject {

            c.like = isLiked
            print(c.like)
            helper.saveContext()
        }
    }
    do {
        try helper.persistentContainer.viewContext.execute(asyncFecthRequest)
    } catch {
        print("error")
        return false
    }
    return true
}

func updateComments(id: Int, comments: String) -> Bool {
    let fetchRequest: NSFetchRequest = News.fetchRequest()
    fetchRequest.predicate = NSPredicate(format: "newsid == %i", Int16(id))
    let asyncFecthRequest = NSAsynchronousFetchRequest(fetchRequest: fetchRequest) { (result: NSAsynchronousFetchResult!) in
        let fetchObject = result.finalResult!
        for c in fetchObject {
            c.comment = comments
            print(c.comment as Any)
            helper.saveContext()
        }
    }
    do {
        try helper.persistentContainer.viewContext.execute(asyncFecthRequest)
    } catch {
        print("error")
        return false
    }
    return true
}



func updateAccess(id: Int, access: Int16) -> Bool {
    let fetchRequest: NSFetchRequest = News.fetchRequest()
    fetchRequest.predicate = NSPredicate(format: "newsid == %i", Int16(id))
    let asyncFecthRequest = NSAsynchronousFetchRequest(fetchRequest: fetchRequest) { (result: NSAsynchronousFetchResult!) in
        let fetchObject = result.finalResult! 
        for c in fetchObject {
            c.access = access
            print(c.access)
            helper.saveContext()
        }
    }
    do {
        try helper.persistentContainer.viewContext.execute(asyncFecthRequest)
    } catch {
        print("error")
        return false
    }
    return true
}
func loadComment(id: Int) -> Array<String> {
    var temp: Array<String> = []
    let news = findNewsbyId(id)
    let comments = news[0].comment

    let commentArray: Array<String> = (comments?.components(separatedBy: "%%"))!
    print(commentArray.count)
    print(commentArray)
    for i in 0...commentArray.count - 1 {
        if !commentArray[i].isEmpty {
            temp.append(commentArray[i])

        }
    }
    print(temp)
    return temp
}


func fetchAll() -> [News] {
    let fetchRequest: NSFetchRequest = News.fetchRequest()
    //fetchRequest.sortDescriptors = [NSSortDescriptor(key: "age", ascending: true)]
    do {
        let result = try helper.persistentContainer.viewContext.fetch(fetchRequest)
        return result
    } catch let err {
        print("core data fetch all error:", err)
    }
    return [News]()
}
func fetchCount() -> Int {
    let context = helper.persistentContainer.viewContext
    var result = 0;
    let fetchRequest: NSFetchRequest = News.fetchRequest()
    fetchRequest.resultType = .countResultType
    do {
        result = try context.count(for: fetchRequest)
        print("count: ", result)
    } catch let err {
        print("core data fetch all error:", err)
    }
    return result;
}


